package wujinye.com.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class BaseServlet extends HttpServlet {

    public BaseServlet() {
        super();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        uri = uri.replace(req.getContextPath(), "");
        //这个到时候做一个日志打印记录，暂时不删
        System.out.println("servlet请求的url：" + uri);
        String[] split = uri.split("/");
        Class<? extends BaseServlet> servletClass = this.getClass();
        //通过反射，找到那一层的servlet
        String className = servletClass.getName();
        try {
            Class<?> aClass = Class.forName(className);
            //实例化那个servlet
            Object obj = aClass.newInstance();
            String methodName = split[2];
            //通过反射，找到方法，并且用代理，去执行它
            Method method = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(obj,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
